<template>
    <div>
        <div class="header">
            <div class="">
                <el-button size="default" @click="start" :icon="Search" type="primary"> 查询 </el-button>
                <!-- <router-link :to="{ name: '添加专题' }" custom v-slot="{ navigate }"> -->
                <el-button size="default" @click="dialogVisible = true" type="primary">
                    + 导入团队专题
                </el-button>
                <!-- </router-link> -->
                <!-- <el-button size="default" @click="updateSort">修改排序</el-button> -->
            </div>
        </div>
        <div class="">
            <div class="">
                <!-- @selection-change="handleChange" :highlight-current-row="!!userhandleCurrentChange"
                @current-change="userCurrentChange"
                @cell-click="userhandleCurrentChange ? userhandleCurrentChange : () => { }" -->
                <el-table :data="tableData" border height="73vh" style="width: 100%" @sort-change="sortchange">
                    <template v-slot:empty>
                        <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
                    </template>
                    <el-table-column label="ID" prop="ID" sortable></el-table-column>
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="题目数" prop="questionquestionbankcount">
                        <template #default="{ row }">
                            {{ row?.questionquestionbank?.length }}
                        </template>
                    </el-table-column>
                    <el-table-column label="答题记录" prop="userquestioncount"></el-table-column>
                    <el-table-column label="标签" prop="label"></el-table-column>
                    <el-table-column label="创建时间" prop="createdAt" sortable
                        :formatter="({ createdAt }) => formatDate({ updatedAt: createdAt })">
                    </el-table-column>
                    <el-table-column label="操作" width="240">
                        <template #default="{ row }">
                            <!-- <router-link :to="{ name: '添加专题', query: { ID: row.ID } }" custom
                                v-slot="{ navigate }">
                                <el-button size="default" type="warning" @click="navigate">修改</el-button>
                            </router-link> -->
                            <el-button size="default" @click="del(row.ID)" type="danger">删除</el-button>
                            <el-button plain type="">
                                <a target="_blank" :href="`${pdfBaseUrl}/question.html?questionbankid=${row.ID}&title=${row.name}`"
                                    type="primary">保存专题为pdf</a>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="row mb-1">
            <div class="col">
                <el-pagination class="pager" :total="totalCount" :page-size="Number(limit)" :page-sizes="pageSizes"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    layout="total, sizes,prev, pager, next"></el-pagination>
            </div>
        </div>
        <!-- 修改排序 -->
        <el-dialog v-model="dialogVisibleUpdateSort" title="Tips" width="700px">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    修改排序
                </span>
            </template>
            <div>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <td width="100" class="text-center">ID</td>
                            <td width="100" class="text-center">排序</td>
                            <td class="text-center">名称</td>
                        </tr>
                    </thead>
                    <vuedraggable tag="tbody" v-model="questionbanks" item-key="ID">
                        <template #item="{ element, index }">
                            <tr>
                                <td>{{ element.ID }}</td>
                                <td>{{ element.top }}</td>
                                <td class="text-center">
                                    {{ element.name }}
                                </td>
                            </tr>
                        </template>
                    </vuedraggable>
                </table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisibleUpdateSort = false">取消</el-button>
                    <el-button type="primary" @click="confirmUpdateSort">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!--  -->
        <el-dialog v-model="dialogVisible" v-if="dialogVisible" title="选择专题" width="840px" height="100vh" top="0"
            :before-close="start">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    选择专题
                </span>
            </template>
            <Addselectquestionbank :addclick="addclick" :teamid="teamId">
            </Addselectquestionbank>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, ref } from "vue";
import vuedraggable from 'vuedraggable';
import { useStore } from "vuex";
import {
    Iobj,
    asyncaddquestionbankteam,
    asynccreateorupdatequestionbank,
    asyncdelquestionbankteam,
    asyncselectquestionbank
} from "../../../api/index";
import { Storekey } from "../../../interface";
import { default as Studycodemodel, default as study } from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
import Addselectquestionbank from "./addselectquestionbank.vue";

const pdfBaseUrl = process.env.NODE_ENV === 'production' ? 'https://oj.hterobot.com' : '';

const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
    return store.getters.getuser;
});
const teamId = computed(() => {
    return Number(user.value?.teamid)
})

const sortable = ref('DESC')
const offset = ref(0)
const limit = ref(20)
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const order = ref('ID')
const like = ref()
const dialogVisibleUpdateSort = ref(false)

const questionbanks = ref<study.Iquestionbank[]>([])
const _questionbanks = ref<study.Iquestionbank[]>([])

const tableData = ref<study.Iquestionbank[]>([])
const totalCount = ref(0)

async function start() {
    try {
        let _like: [keyof study.Iquestionbank, string | number] | undefined;

        if (like.value) {
            _like = ["name", like.value];
        }
        const query: Iobj<study.Iquestionbank> = {
            _limit: limit.value,
            _offset: offset.value,
            _order: order.value,
            _sortable: sortable.value,
            _like,
            teamid: teamId.value,
            usertype: "team",
        }
        const { rows, count } = await asyncselectquestionbank(query);
        tableData.value = rows
        totalCount.value = count

        dialogVisible.value = false

    } catch (e: any) {
        ElMessage.error(e);
    }
}

onMounted(() => {
    start()
})

function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
    start()
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}
// 修改排序
async function updateSort() {
    const data = await asyncselectquestionbank({
        usertype: 'team',
        teamid: teamId.value,
        _order: 'top',
        _sortable: 'ASC'
    })
    questionbanks.value = data.rows.map(e => {
        return {
            ID: e.ID,
            name: e.name,
            top: e.top
        }
    })
    _questionbanks.value = data.rows
    dialogVisibleUpdateSort.value = true
}
async function confirmUpdateSort() {
    const n = questionbanks.value.map((e, k) => {
        const { top } = _questionbanks.value[k]
        if (top === e.top) {
            return undefined
        }
        return {
            ID: e.ID,
            top,
        }
    }).filter(e => e)
    const c = n.map(e => {
        if (e) {
            return asynccreateorupdatequestionbank(e)
        }
    })
    Promise.all(c).then(() => {
        dialogVisibleUpdateSort.value = false
    })
    ElMessage.success('修改完成')
}

// 
function sortchange(row: { prop: any; order: any }) {
    const { prop, order } = row;
    console.log(prop, order, order == "descending")
    if (order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    if (prop) {
        order.value = prop;
    }
}
function formatDate({ updatedAt }: any) {
    return toLocaleDateString(updatedAt);
}
// function handleChange(data: study.Iquestionbank[]) {
//     if (p.handleSelectionChange) p.handleSelectionChange(data);
// }
// function userCurrentChange(data: study.Iquestionbank) {
//     if (p.userhandleCurrentChange) p.userhandleCurrentChange(data);
// }

function del(ID: number) {
    try {
        ElMessageBox.confirm("确定要删除此题单, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asyncdelquestionbankteam({ questionbankid: ID, teamid: teamId.value });
                ElMessage({
                    message: "删除成功",
                    type: "success",
                });
                start()
            })
            .catch(() => {
                ElMessage({
                    type: "info",
                    message: "已取消删除",
                });
            });

    } catch (e: any) {
        ElMessage({
            message: "删除失败" + e,
            type: "error",
        });
    }
}

// 添加题单
const dialogVisible = ref(false)
async function addclick(v: Studycodemodel.Iquestionbank) {
    await asyncaddquestionbankteam({ questionbankid: v.ID, teamid: teamId.value }).then(() => {
        ElMessage.success('添加成功')
    }).catch(f => {
        ElMessage.error(f)
    })
}

</script>

<style scoped>
.header {
    margin-bottom: 20px;
}

.pager {
    margin-top: 20px;
    float: right;
}
</style>